//
//  ViewController.m
//  Example13-2b
//
//  Created by 孙晓晔 on 2017/4/24.
//  Copyright © 2017年 孙晓晔. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property(nonatomic,assign) int ticket;

@property(nonatomic,strong) NSLock *myLock;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.ticket = 10;
    
    
    [self bb];
}

-(void)bb {
    
    NSBlockOperation *op1 = [[NSBlockOperation alloc]init];
    [op1 addExecutionBlock:^{
        while (self.ticket > 0) {
            
            @synchronized (self) {
                if (self.ticket < 1) {
                    return;
                }
                
                self.ticket--;
                
                NSLog(@"线程 = %@卖出一张，还剩%d张", [NSThread currentThread], self.ticket);
            }
        }
    }];
    
    NSBlockOperation *op2 = [[NSBlockOperation alloc]init];
    [op2 addExecutionBlock:^{
        while (self.ticket > 0) {
            
            @synchronized (self) {
                if (self.ticket < 1) {
                    return;
                }
                
                self.ticket--;
                
                NSLog(@"线程 = %@卖出一张，还剩%d张", [NSThread currentThread], self.ticket);
            }
        }
    }];
    
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    
    [queue addOperation:op1];
    [queue addOperation:op2];
    
}

-(void)aa {
    NSThread *op1 = [[NSThread alloc]initWithTarget:self selector:@selector(run1) object:nil];
    
    NSThread *op2 = [[NSThread alloc]initWithTarget:self selector:@selector(run1) object:nil];
    
    [op1 start];
    [op2 start];
}

-(void)run1 {
    
    while (self.ticket > 0) {
        
        [_myLock lock];
            if (self.ticket < 1) {
                return;
            }
                
            self.ticket--;
            
            NSLog(@"线程 = %@卖出一张，还剩%d张", [NSThread currentThread], self.ticket);
            
        [_myLock unlock];
        
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
